package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.constants.FollowBehaviorConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    ApUserFollowMapper apUserFollowMapper;

    @Autowired
    ApUserFanMapper apUserFanMapper;

    /**
     * 用户关注/取消关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1 参数校验
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2 远程调用查询作者的信息
        ApAuthor apAuthor = articleFeign.findById(dto.getAuthorId());
        if (apAuthor == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "作者已被锁定");
        }

        //3 判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //4 关注/取消关注
        if (dto.getOperation().intValue() == 0) {  // 关注
            return followByUserId(user.getId(), apAuthor.getUserId(), dto.getArticleId());
        }else { // 取消关注
            return followCancelByUserId(user.getId(), apAuthor.getUserId());

        }
    }

    /**
     * 取消关注
     * @param userId  当前登录用户ID
     * @param followUserId 当前用户关注的 作者对应的 APUser Id
     * @return
     */
    private ResponseResult followCancelByUserId(Integer userId, Integer followUserId) {

        // 1 删除我的关注
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, userId)
                .eq(ApUserFollow::getFollowId, followUserId)
        );

        // 2 删除作者的粉丝
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId, followUserId)
                .eq(ApUserFan::getFansId, userId )
        );

        // 3 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    @Autowired
    KafkaTemplate kafkaTemplate;

    /**
     * 关注
     * @param userId  当前登录用户ID
     * @param followUserId 当前用户关注的 作者对应的 APUser Id
     * @param articleId 文章id
     * @return
     */
    private ResponseResult followByUserId(Integer userId, Integer followUserId, Long articleId) {
        //1 查询作者的用户id是否存在
        ApUser apUser = apUserMapper.selectById(followUserId);
        if (apUser == null || apUser.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "被关注自媒体人已被锁定");
        }

        //2 是否关注自己
        if (userId.equals(followUserId)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "无需关注自己");
        }

        //3 保存我的关注  关注数据
        // 是否已关注该作者
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, userId)
                .eq(ApUserFollow::getFollowId, followUserId)
        );
        if (apUserFollow != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "无需重复关注");
        }
        apUserFollow = new ApUserFollow();
        apUserFollow.setFollowId(followUserId);
        apUserFollow.setFollowName(apUser.getName());
        apUserFollow.setUserId(userId);
        apUserFollow.setLevel((short)1);
        apUserFollow.setIsNotice(true);
        apUserFollow.setCreatedTime(new Date());
        apUserFollowMapper.insert(apUserFollow);


        //4 保存作者对应的 粉丝数据
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId, followUserId)
                .eq(ApUserFan::getFansId, userId )
        );
        if (apUserFan != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        apUserFan = new ApUserFan();
        apUserFan.setCreatedTime(new Date());
        apUserFan.setLevel((short)0);
        apUserFan.setIsShieldComment(false);
        apUserFan.setIsShieldLetter(false);
        apUserFan.setIsDisplay(true);
        apUserFan.setFansId(userId.longValue());

        // 查询粉丝名称
        ApUser fansUser = apUserMapper.selectById(userId);
        if (fansUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST);
        }
        apUserFan.setFansName(fansUser.getName());

        apUserFan.setUserId(followUserId);
        apUserFanMapper.insert(apUserFan);

        //5 异步记录用户关注行为
        //发消息
        FollowBehaviorDto followBehaviorDto =
                new FollowBehaviorDto(articleId,followUserId, userId);
        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(followBehaviorDto));

        //6 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
